import { Divider } from 'vant';
<template>
	<div class="push">
		<!-- <van-nav-bar fixed left-text="返回" left-arrow :title="!isWeixin() ? '发布转单' : ''" @click-left="handleBack" /> -->
		<div class="push-form">
			<van-form ref="pushFormEle" label-width="100">
				<van-cell-group inset>
					<van-field required label="行业" :rules="[{ required: true, message: '请选择' }]"
						v-model="pushForm.classify" is-link readonly name="classify" placeholder="请选择"
						@click="showPicker = true" />
					<van-field name="title" required v-model="pushForm.title" label="标题" placeholder="请输入"
						:rules="[{ required: true, message: '请填写' }]" />
					<van-field name="content" v-model="pushForm.content" rows="3" autosize label="描述" type="textarea"
						placeholder="请填写需求描述" />
					<van-field required name="num" v-model="pushForm.num" placeholder="请输入" type="number" label="需求数量"
						:rules="[{ required: true, message: '请填写' }]" />
					<van-field required name="name" v-model="pushForm.name" label="联系人" placeholder="请输入"
						:rules="[{ required: true, message: '请填写' }]" />
					<van-field required name="phone" v-model="pushForm.phone" placeholder="请输入" type="tel" label="联系电话"
						:rules="[{ required: true, message: '请填写' }]" />
					<van-field :rules="[{ required: true, message: '请选择' }]" required is-link readonly name="area"
						v-model="pushForm.area" label="需求地点" placeholder="请选择" @click="showArea = true" />
					<van-field name="price" required v-model="pushForm.price" type="number" placeholder="请输入"
						label="线索价格" :rules="[{ required: true, message: '请填写' }]" />
					<!-- <van-field required name="num2" v-model="pushForm.num2" type="number" placeholder="请输入" label="销售数量"
            :rules="[{ required: true, message: '请填写' }]" /> -->
				</van-cell-group>
				<div style="margin: 16px">
					<van-button round block type="primary" @click="submit">
						发布转单
					</van-button>
				</div>
			</van-form>
			<van-tabbar :safe-area-inset-bottom="true" route>
				<van-tabbar-item replace url="https://wx.yewudaotech.com/supply.html" icon="home-o">列表</van-tabbar-item>
				<van-tabbar-item replace to="/businesspush" icon="guide-o">发布</van-tabbar-item>
				<van-tabbar-item replace to="/user" icon="contact-o">我的</van-tabbar-item>
			</van-tabbar>
			<van-popup v-model:show="showPicker" position="bottom">
				<van-picker :columns-field-names="{ text: 'title', value: 'value' }" :columns="columns"
					@confirm="onConfirmJob" @cancel="showPicker = false" />
			</van-popup>
			<van-popup v-model:show="showArea" position="bottom">
				<van-area :columns-field-names="{ text: 'name', value: 'id', children: 'List' }" :columns="areaList"
					@confirm="onConfirmArea" @cancel="showArea = false" />
			</van-popup>
			<BindPhone :show="bindPhoeShoe" @cancel="handlePhoneCancel" @confirm="handleBindPhoneConfirm"></BindPhone>
		</div>
	</div>
</template>
<script setup lang="ts">
	import { BindPhone } from "@/components";
	import { getCookie } from "@/utils/index";
	import { ref, reactive } from "vue";
	import { useRouter, useRoute, LocationQueryValue } from "vue-router";

	import { showLoadingToast, showSuccessToast, showFailToast, showConfirmDialog, showToast } from 'vant';
	import { isWeixin } from "@/utils/index";
	import { classifysApi, procureaddApi, provincesApi } from "@/api/push";
	import { userInfoApi } from '@/api/user'
	import { userphoneApi } from '@/api/detail'
	import { login } from "@/api/home"
	import wxchat from "@/utils/wechartSdk";
	const router = useRouter();
	const columns = ref<any>([]);
	const areaList = ref([])
	const showPicker = ref(false);
	const showArea = ref(false);
	const pushFormEle = ref()
	const bindPhoeShoe = ref(false)
	const pushForm = reactive({
		classify: "",
		title: "",
		content: "",
		num: "",
		name: "",
		phone: "",
		area: "",
		price: "",

	});
	const currentClassifys = ref<any>()
	const currentArea = ref<any>()
	// hdd 2024-6-19新增转发分享
	const route = useRoute();
	let pid : string | LocationQueryValue[];
	pid = route.query.pid ? route.query.pid : '';
	const preLogin = () => {
		let code = getCookie("code") ? getCookie("code") : "";
		login({ code: code, pid: Number(pid) }).then((res) => {

		});
	}
	preLogin();
	// ******************************************
	const handlePhoneCancel = () => {
		bindPhoeShoe.value = false
	}
	const handleBindPhoneConfirm = async (phone : string) => {
		bindPhoeShoe.value = false
		let loading = showLoadingToast({
			duration: 0,
			message: '请稍后...',
			forbidClick: true,
		});
		let { code, msg } = await userphoneApi({ uid: getCookie("token") ? Number(getCookie("token")) : '', phone })
		if (code === 0) {
			loading.close()
			showSuccessToast({
				message: '绑定成功',
				position: 'top'
			})
		} else {
			showToast({
				message: msg,
				position: 'top'
			})
		}

	}
	const getClassifys = () => {
		classifysApi({}).then((res) => {
			if (res.code == 0) {
				columns.value = res.data || []
				if (columns.value.length) {
					pushForm.classify = columns.value[0]?.title
					currentClassifys.value = columns.value[0]
				}
			} else {
				columns.value = []
			}
		})
	}

	const getProvinces = () => {
		provincesApi({}).then((res) => {
			if (res.code == 0) {
				areaList.value = res.data || []
			} else {
				areaList.value = []
			}
		})
		wxchat.share({
			title: "邀请你来转单宝，每月多赚3万块",
			desc: "老铁，你手里要是有做不了的单子，可以到这个平台上去发布，我都赚了3万块了，还有很多单子可以接",
			link: window.location.href.split("#")[0] + '?pid=' + Number(getCookie("token")),
			// link: window.location.href.split("#")[0],
			image: "http://zdb.suishilian.com/upload/yyb.jpg",
		});
	}
	getProvinces()
	getClassifys()
	const handleBack = () => {
		if (history.state?.back) {
			router.back()
		} else {
			router.push('/user')
		}
	};


	const onConfirmJob = ({ selectedOptions } : any) => {
		console.log(selectedOptions[0])
		currentClassifys.value = selectedOptions[0]
		pushForm.classify = selectedOptions[0].title
		showPicker.value = false
	};
	const onConfirmArea = ({ selectedOptions } : any) => {

		currentArea.value = selectedOptions
		pushForm.area = selectedOptions[1].name
		showArea.value = false

	};
	const submit = async () => {
		let userData = await userInfoApi({ uid: getCookie('token') ? Number(getCookie('token')) : '', })
		console.log(userData)
		if (!userData?.data?.phone) {
			bindPhoeShoe.value = true
			return
		}
		pushFormEle.value.validate().then(() => {

			let toast = showLoadingToast({
				message: '提交中...',
				loadingType: 'spinner',
				forbidClick: true,
				duration: 0
			});
			let req = {
				uid: getCookie('token') ? Number(getCookie('token')) : '',
				classifyid: currentClassifys.value.id,
				classifytitle: currentClassifys.value.title,
				classifyvalue: currentClassifys.value.value,
				province: currentArea.value[0]?.name,
				provinceid: currentArea.value[0]?.id,
				city: currentArea.value[1]?.name,
				cityid: currentArea.value[1]?.id,
				county: currentArea.value[2]?.name,
				countyid: currentArea.value[2]?.id,
				title: pushForm.title,
				content: pushForm.content,
				num: Number(pushForm.num),
				price: Number(pushForm.price),
				name: pushForm.name,
				phone: pushForm.phone
			}
			procureaddApi(req).then((res) => {
				toast.close()
				if (res.code == 0) {
					showSuccessToast({
						message: '发布成功',
						duration: 1500,
						forbidClick: true,
						onClose: () => {
							router.push('/user')
						}
					})
				} else {
					showFailToast(res.msg)
				}
			}
			)
			console.log(req)
		})

	}
</script>
<style lang="scss" scoped>
	@import "./index.scss";
</style>